//
//  AppDelegate+WeixinConfig.m
//  WC
//
//  Created by wsj2015 on 16/1/12.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "AppDelegate+WeixinConfig.h"
#import "WCPopupLayerManager.h"
#import "JCAlertView.h"
#import "WCNJoinMeetingVC.h"
#import "WCNNavigationController.h"
#import "Constants.h"
#import "WCNTabBarVC.h"
#import "NSString+Utilities.h"
#import "WCNAppDelegate.h"

#define MEETING_PARAM @"iphone"
@implementation WCNAppDelegate(Weixin)



- (void)wexinApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    //向微信注册
    BOOL isOk= [WXApi registerApp:@"wxcb249b2ae88c1721" withDescription:@"wcn"];
    if (isOk) {
        Log(@"微信初始化成功");
    }
    
    

    
}

#pragma mark - 适配 10 以前的方法
//-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
//{
//    return [self application:app openURL:url sourceApplication:nil annotation:nil];
//
//}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    
   

    //通过连接打开app
    NSRange range = [url.scheme rangeOfString:@"zhumumeeting"];
    if (range.length >0) {
//        NSLog(@"sourceApplication: %@", sourceApplication);
//        NSLog(@"URL scheme:%@", [url scheme]);
//        NSLog(@"URL query: %@", [url query]);
        
        // 接受传过来的参数
         WCNAppDelegate *delegate = (WCNAppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.isFromDevtip = YES;
        NSArray *dicArr = [NSString getParamsFromUrlArray:@[url.absoluteString]];
        if (dicArr.count<=0) {
            return YES;
        }
        NSDictionary *dict = dicArr.firstObject;
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"打开啦"
                                                            message:dict[MEETING_PARAM]
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [[NSNotificationCenter defaultCenter] postNotificationName:DevtipNotification object:nil];
        if ([[WCDefaultManager shareMg] account]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
                
                WCNNavigationController *nav = (WCNNavigationController *)[[UIApplication sharedApplication].delegate window].rootViewController;
                for (UIViewController *VC in nav.viewControllers) {
                    if ([VC isKindOfClass:[WCNJoinMeetingVC class]]) {
                        WCNJoinMeetingVC *mVC = (WCNJoinMeetingVC *)VC;
                        mVC.meetingID = dict[MEETING_PARAM];
                         return ;
                    }
                }
                WCNJoinMeetingVC *vc = [WCNJoinMeetingVC new];
                vc.meetingID = dict[MEETING_PARAM];
                [nav pushViewController:vc animated:YES];
            });
            
        }else{
           
           
            [[NSNotificationCenter defaultCenter] addObserverForName:UserLoginFromDevtipNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    UIAlertView *myalertView = [[UIAlertView alloc] initWithTitle:@"打开啦"
                                                                          message:dict[MEETING_PARAM]
                                                                         delegate:nil
                                                                cancelButtonTitle:@"OK"
                                                                otherButtonTitles:nil];
                    [myalertView show];
                    WCNTabBarVC *mainVC = [[WCNTabBarVC alloc] init];
                    
                    WCNNavigationController *nav = (WCNNavigationController *)[[UIApplication sharedApplication].delegate window].rootViewController;
                    NSMutableArray *muA = [NSMutableArray arrayWithArray:nav.viewControllers];
                    WCNJoinMeetingVC *vc = [WCNJoinMeetingVC new];
                    vc.meetingID = dict[MEETING_PARAM];
//                    [muA addObjectsFromArray:@[mainVC,[WCNJoinMeetingVC new]]];
                    [nav setViewControllers:@[mainVC,vc]];
                    //                    [nav pushViewController: [WCNJoinMeetingVC new] animated:NO];
                    [[NSNotificationCenter defaultCenter] removeObserver:self];
                    
                });
                
            }];
           
        }
        return YES;
    }
    
    BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
    NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
    return  isSuc;
}



- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}



-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.tag = 1000;
        [alert show];
        
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%u bytes\n\n", msg.title, msg.description, obj.extInfo, msg.thumbData.length];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        NSString *strMsg = @"这是从微信启动的消息";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
      
    }
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
//        NSString *strTitle = [NSString stringWithFormat:@"分享结果"];
        if (resp.errCode == 0) {
            [CoreSVP showSVPWithType:CoreSVPTypeSuccess Msg:@"分享成功" duration:2.0f allowEdit:NO beginBlock:nil completeBlock:nil];
        }else{
            [CoreSVP showSVPWithType:CoreSVPTypeError Msg:@"分享失败" duration:2.0f allowEdit:NO beginBlock:nil completeBlock:nil];
        
        }
//        NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alert show];
       
    }
}
@end
